﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 

using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
 
using Dapper;
 

namespace DAL
{
    public class DapperHelper<T>
    {
        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        private static string connectionString = "server=.;database=watercloudnetdb;uid=sa;pwd=sa123456;";
        //private static string connectionString = "server=1.13.181.15;database=watercloudnetdb;uid=sa;pwd=Admin@123;";
        //public static string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ToString();

        private static SqlConnection connection;
        public static SqlConnection Connection
        {
            get
            {
                if (connection == null)
                {
                    connection = new SqlConnection(connectionString);
                    connection.Open();
                }
                else if (connection.State == ConnectionState.Closed)
                {
                    connection.Open();
                }
                else if (connection.State == ConnectionState.Broken)
                {
                    connection.Close();
                    connection.Open();
                }
                return connection;
            }
        }


        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="sql">查询的sql</param>
        /// <param name="param">替换参数</param>
        /// <returns></returns>
        public static List<T> Query(string sql, object param)
        {
            return Connection.Query<T>(sql, param).ToList();
        }

        public static List<T> Query(string sql)
        {
            return Connection.Query<T>(sql).ToList();
        }


        public static DataTable getDataTable(string sql)
        {
            DataTable dt = new DataTable();
            var read = Connection.ExecuteReader(sql);

            dt.Load(read);

            return dt;

            //return Connection.Query<T>(sql).ToList();

        }

      

        /// <summary>
        /// 查询第一个数据
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static T QueryFirst(string sql, object param)
        {

            return Connection.QueryFirst<T>(sql, param);

        }

        public static T QueryFirst(string sql)
        {

            return Connection.QueryFirstOrDefault<T>(sql);
        }

        /// <summary>
        /// 查询第一个数据没有返回默认值
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static T QueryFirstOrDefault(string sql, object param)
        {

            return Connection.QueryFirstOrDefault<T>(sql, param);

        }

        public static T QueryFirstOrDefault(string sql)
        {

            return Connection.QueryFirstOrDefault<T>(sql);

        }

        /// <summary>
        /// 查询单条数据
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static T QuerySingle(string sql, object param)
        {

            return Connection.QuerySingle<T>(sql, param);

        }

        /// <summary>
        /// 查询单条数据没有返回默认值
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static T QuerySingleOrDefault(string sql, object param)
        {

            return Connection.QuerySingleOrDefault<T>(sql, param);

        }

        public static T QuerySingleOrDefault(string sql)
        {

            return Connection.QuerySingleOrDefault<T>(sql);

        }

        /// <summary>
        /// 增删改
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static int Execute(string sql, object param)
        {
            try
            {
                return Connection.Execute(sql, param);
            }
            catch (Exception es)
            {
                return 0;
            }


        }

        public static int Execute(string sql)
        {

            return Connection.Execute(sql);

        }

        /// <summary>
        /// Reader获取数据
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static IDataReader ExecuteReader(string sql, object param)
        {

            return Connection.ExecuteReader(sql, param);

        }

        /// <summary>
        /// Scalar获取数据
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static object ExecuteScalar(string sql, object param)
        {
            return Connection.ExecuteScalar(sql, param);
        }

        /// <summary>
        /// Scalar获取数据
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static object ExecuteScalar(string sql)
        {
            return Connection.ExecuteScalar(sql);
        }

        /// <summary>
        /// Scalar获取数据
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static T ExecuteScalarForT(string sql, object param)
        {

            return Connection.ExecuteScalar<T>(sql, param);

        }

        /// <summary>
        /// 带参数的存储过程
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static List<T> ExecutePro(string proc, object param)
        {

            List<T> list = Connection.Query<T>(proc,
                param,
                null,
                true,
                null,
                CommandType.StoredProcedure).ToList();
            return list;

        }


        /// <summary>
        /// 事务1 - 全SQL
        /// </summary>
        /// <param name="sqlarr">多条SQL</param>
        /// <param name="param">param</param>
        /// <returns></returns>
        public static int ExecuteTransaction(List<string> sqlarr)
        {

            using (var transaction = Connection.BeginTransaction())
            {
                try
                {
                    int result = 0;
                    foreach (var sql in sqlarr)
                    {
                        result += Connection.Execute(sql, null, transaction);
                    }

                    transaction.Commit();
                    return result;
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    return 0;
                }
            }

        }

        /// <summary>
        /// 事务2 - 声明参数
        ///demo:
        ///dic.Add("Insert into Users values (@UserName, @Email, @Address)",
        ///        new { UserName = "jack", Email = "380234234@qq.com", Address = "上海" });
        /// </summary>
        /// <param name="Key">多条SQL</param>
        /// <param name="Value">param</param>
        /// <returns></returns>
        public static int ExecuteTransaction(List<Tuple<string, object>> dic)
        {

            SqlTransaction transaction = Connection.BeginTransaction();

            try
            {

                int result = 0;
                foreach (var sql in dic)
                {
                    result += Connection.Execute(sql.Item1, sql.Item2, transaction);
                }

                transaction.Commit();
                return result;
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                return 0;
            }
        }

        //        public static List<T> Query(string sql)
        //        {

        //            string sql = @"select  
        //t.Id,
        //c.modelL,
        //c.modelA,
        //c.modelB,
        //m.mComparisonLow,
        //m.mComparisonHigh,
        //m.mMinSize,
        //m.mPyramidLevel,
        //m.mMinZoom,
        //m.mMaxzoom,
        //m.mZoomStep,
        //m.mAngleStep,
        //m.mMinComparison,
        //m.mTempPath,
        //m.mKnowArea,
        //r.rSymbolWidth,
        //r.rSymbolHeight,
        //r.rdrawWidth,
        //r.rMinFragment,
        //r.rBrightText,
        //r.rTempPath,
        //r.rKnowArea,
        //r.rOCRArea,
        //r.rComparisonLow,
        //r.rComparisonHigh,
        //r.rMinSize,
        //r.rPyramidLevel,
        //r.rMinZoom,
        //r.rMaxzoom,
        //r.rZoomStep,
        //r.rAngleStep,
        //r.rMinComparison,
        //a.aSite,
        //a.aLeftComparison,
        //a.aLeftX,
        //a.aLeftY,
        //a.aLeftXLength,
        //a.aLeftYLength,
        //a.aRightComparison,
        //a.aRightX,
        //a.aRightY,
        //a.aRightXLength,
        //a.aRightYLength
        //from hy_Order o
        //left join  hy_Template t on t.tEname=o.TTemplate
        //left join  hy_TempColor c on c.tid=t.id
        //left join  hy_TempMatch m on m.tId=t.id
        //left join  hy_TempOCR r on r.tId=t.id
        //left join  hy_TempDoorAlign a on a.tId=t.id";


        //            var data = Connection.Query<hy_Order, hy_Template, hy_TempColor, hy_TempMatch, hy_TempOCR, hy_TempDoorAlign>(
        //                sql, (o,t,c,m,r,a) => {
        //                //u.Movies = m; u.MyTYC.Add(t); return u; 
        //            });

        //        }

    }
}

        
    
 

